package com.zis.platform.common.mybatis;

import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.jsqlparser.JSQLParserException;

import org.apache.log4j.Logger;

import com.zis.platform.common.mybatis.sqlparser.SqlParserUtil;
import com.zis.platform.common.util.CacheCoreUtil;
import com.zis.platform.core.entity.DataAuthStrategyEntity;
import com.zis.platform.core.entity.DataAuthUserEntity;

/**
 * 
 * <b>说明：</b>SQL查询语句的格式化
 * 
 * @ClassName: DataAccessFilter
 * @author zhaohaitao(2543)
 * @date 2015-7-10 上午10:13:39
 * 
 */
public class DataAccessFilter
{
    private Logger log = Logger.getLogger(DataAccessFilter.class);
    
    private static final String OFFSET = "OFFSET";
    
    protected String checkDataPermissions(String sql, Map<String, List<DataAuthUserEntity>> dataPermission)
        throws JSQLParserException
    {
        try
        {
            return changDataSql(sql, dataPermission);
        }
        catch (Exception e)
        {
            log.error("SQL语句格式化错误。" + e.getMessage());
        }
        return null;
    }
    
    private String changDataSql(String sql, Map<String, List<DataAuthUserEntity>> dataPermission)
        throws JSQLParserException
    {
        Map<String, DataAuthStrategyEntity> allDataAuthStrategy = CacheCoreUtil.getAllDataAuthStrategy();
        Set<String> keySet = allDataAuthStrategy.keySet();
        List<String> tableNames = SqlParserUtil.getTableNames(sql);
        for (String tableName : keySet)
        {
            if (tableNames.contains(tableName))
            {
                List<DataAuthUserEntity> list = dataPermission.get(tableName);
                DataAuthStrategyEntity dataAuthStrategy = allDataAuthStrategy.get(tableName);
                String sqlString = dataAuthStrategy.toString(list);
                sql = SqlParserUtil.changeSql(sql.toUpperCase(), sqlString, tableName);
                if (sql.toUpperCase().indexOf(OFFSET) > -1)
                {
                    sql = sql.replace(OFFSET, ",");
                }
            }
        }
        return sql;
    }
    
}